package com.atguigu.srb.sms.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.clients.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

//@CrossOrigin
@RestController
@RequestMapping("/api/sms")
public class ApiSmsController {

    @Autowired
    SmsService smsService;

//    @Qualifier("CoreUserInfoClient")
//    @Autowired
    @Resource
    CoreUserInfoClient coreUserInfoClient;

    @GetMapping("/sendRegisterCode/{mobile}")
    public R sendRegisterCode(@PathVariable("mobile") String mobile){
        //手机号存在返回true不存在返回false
        boolean mobileExist = coreUserInfoClient.isMobileExist(mobile);
        Assert.isTrue(!mobileExist,ResponseEnum.MOBILE_EXIST_ERROR);
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        boolean b = RegexValidateUtils.checkCellphone(mobile);
        Assert.isTrue(b,ResponseEnum.MOBILE_ERROR);
        smsService.sendRegisterCode(mobile);
        return R.ok();
    }



    public static void main(String[] args) throws ClientException {

        // 设置公共参数
        DefaultProfile defaultProfile = DefaultProfile.
                getProfile("cn-beijing",
                        "LTAI5tKKDm1DNyCJWbZmvmTA",
                        "NO0WEOHoSFhN2fDz4QF8a3IUQNKrxG");

        // 阿里云客户端工具
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);

        // 配置请求参数
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setSysAction("SendSms");
        commonRequest.setSysMethod(MethodType.POST);
        commonRequest.setSysVersion("2017-05-25");
        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");// 阿里网关
        commonRequest.putQueryParameter("PhoneNumbers","18999250406");
        commonRequest.putQueryParameter("SignName","阿里云短信测试");
        commonRequest.putQueryParameter("TemplateCode","SMS_154950909");
        Map<String,Object> map = new HashMap<>();
        map.put("code","123456");
        String TemplateParam = JSON.toJSONString(map);
        commonRequest.putQueryParameter("TemplateParam",TemplateParam);


        // 发送短信
        CommonResponse commonResponse = iAcsClient.getCommonResponse(commonRequest);

        // 解析返回结果
        boolean success = commonResponse.getHttpResponse().isSuccess();

    }

}
